﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Runtime.Remoting.Channels;
using System.Net;
using System.Threading;

namespace WinFormStore.BackManager.SocketTool
{
    delegate void AddUserInfoDel(string userInfo, bool isRemove);
    delegate void AddReceiveInfoDel(string str);
    public partial class FrmSocket : Form
    {
        public FrmSocket()
        {
            InitializeComponent();
            myDel += AddUserInfoFunction;
            recvDel += RecMsg;
            this.textBox1.ScrollBars = ScrollBars.Vertical;

        }
        AddUserInfoDel myDel;
        AddReceiveInfoDel recvDel;
        Socket socket;
        Thread th;
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        //private void btnStart_Click(object sender, EventArgs e)
        //{

        //}
        private void Connect()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string ip = "127.0.0.1";
            IPAddress address = IPAddress.Parse(ip);
            string port = "123";
            IPEndPoint endPoint = new IPEndPoint(address, Convert.ToInt32(port));
            try
            {
                socket.Bind(endPoint);
                MessageBox.Show("开启成功");
            }
            catch (Exception)
            {

                throw;
            }
            socket.Listen(10);
            th = new Thread(ListenFunction);
            th.Start();
            btnStart.Enabled = false;
        }
        private void ListenFunction()
        {
            while (true)
            {
                Socket socketClient = socket.Accept();
                string info = socketClient.RemoteEndPoint.ToString();
                dicSocket.Add(info, socketClient);
                Invoke(myDel, info,false);
                Thread th = new Thread(ReceiveInfo);
                th.IsBackground = true;
                th.Start(socketClient);
            }
        }

        private void ReceiveInfo(object obj)
        {
            Socket sckClient = obj as Socket;
            if (sckClient != null)
            {
                while (true)
                {
                    byte[] arrReceive = new byte[1024 * 1024 * 5];
                    int length = -1;
                    length = sckClient.Receive(arrReceive);
                    if (length == 0)
                    {
                        string str = sckClient.RemoteEndPoint.ToString();
                        Invoke(myDel, str, true);
                        break;
                    }
                    else
                    {
                        string str = Encoding.UTF8.GetString(arrReceive, 0, length);
                        string msg = "[接收]" + sckClient.RemoteEndPoint.ToString() + "" + str;
                        Invoke(recvDel, msg);
                    }
                }
            }
        }

        private void AddUserInfoFunction(string strInfo, bool isRemove)
        {
            if (isRemove == true)
            {
                this.listBox1.Items.Remove(strInfo);
            }
            else
            {
                this.listBox1.Items.Add(strInfo);
            }
        }
        private void RecMsg(string str)
        {
            this.textBox1.AppendText(str + "\r\n");
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string textsend = "来自" + LoginConfig.SalesManName + ":" + this.textBox2.Text+DateTime.Now;
            byte[] arrTxt = Encoding.UTF8.GetBytes(textsend);
            if (this.listBox1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要发送的客户端");
            }
            else
            {
                foreach (string item in this.listBox1.SelectedItems)
                {
                    dicSocket[item].Send(arrTxt);
                    string str = "[发送]" + item + textsend;
                    Invoke(recvDel, str);
                }
            }
        }

        private void btnsendall_Click(object sender, EventArgs e)
        {
            string textsend = "来自" + LoginConfig.SalesManName + ":" + this.textBox2.Text + DateTime.Now;
            byte[] arrTxt = Encoding.UTF8.GetBytes(textsend);

            foreach (string item in dicSocket.Keys)
            {
                dicSocket[item].Send(arrTxt);
                string str = "[发送]" + item + textsend;
                Invoke(recvDel, str);
            }

        }

        private void FrmSocket_Load(object sender, EventArgs e)
        {
            Connect();
        }
    }
}
